package com.amigo.online.provider.merchant.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.amigo.online.common.base.security.LocalUser;
import com.amigo.online.common.core.response.Response;
import com.amigo.online.common.param.result.LocalUserInfo;
import com.amigo.online.common.param.result.UserInfo;
import com.amigo.online.common.util.StringUtils;
import com.amigo.online.provider.merchant.common.RwRedisService;
import com.amigo.online.provider.merchant.service.TokenManagerService;
import com.amigo.online.provider.merchant.service.UserFeignService;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;


@Service
public class TokenManagerServiceImpl implements TokenManagerService {

    @Autowired
    UserFeignService userFeignService;
    @Autowired
    RwRedisService rwRedisService;

    @Override
    public boolean checkToken(String token) {
        if (StringUtils.isBlank(token)) {
            return false;
        }
        //如果主reids中有token，则不需要去user服务查找
        LocalUserInfo localUser = (LocalUserInfo) rwRedisService.opsForValue().get(token);
        if (localUser != null) {
            rwRedisService.expire(token, 2592000L);
            LocalUser.setUser(localUser);
            return true;
        }
        ResponseEntity<Response> res = userFeignService.getUserInfoByToken(token);
        if (res.getStatusCodeValue() != 200) {
            return false;
        }
        if (res.getBody() == null) {
            return false;
        }
        if (res.getBody().getMeta().getCode() != 200) {
            return false;
        }
        Object o = res.getBody().getData();
        if (o == null) {
            return false;
        }

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        UserInfo user = objectMapper.convertValue(o, UserInfo.class);
        LocalUserInfo userinfo = new LocalUserInfo();
        userinfo.setToken(token);
        userinfo.setUser(user);
        LocalUser.setUser(userinfo);
        return true;
    }

}
